<template>
  <div class="basic-information-page" @click.stop>
    <div class="pop_up">
      <div class="pop_up_top">
        <div class="pop_up_left"></div>
        <div class="pop_up_name">基础信息</div>
        <div class="pop_up_right"></div>
        <!-- 右上角叉号 -->
        <el-button class="top_right" @click="closeBasicInfo()" type="text">
          <el-icon><Close /></el-icon>
          <!-- <img class="close_icon" src="@/assets/images/close-icon.png" alt="" /> -->
        </el-button>
      </div>
      <div class="pop_up_info">
        <div class="info_add">
          <div class="info_add_name">
            <span style="color: rgba(255, 0, 0, 1)"> *</span>
            公司logo
          </div>
          <div class="info_add_warn">请上传300*300px、JPG/JPEG/PNG的图片</div>
          <div class="add_disabled" @click.stop></div>
          <el-upload
            :action="uploadUrl"
            :file-list="logFileList"
            :before-upload="beforeUploadHandleLog"
            :on-success="successHandleLog"
            :on-error="uploadErrorHandle"
            :limit="1"
            list-type="picture-card"
            :show-file-list="true"
            :auto-upload="true"
            class="brand-upload"
            :on-remove="removeHandleLog"
            :on-preview="handlePictureCardPreview"
          >
            <div class="upload-box" v-if="!dataForm.logo">
              <!-- -->
              <img src="@/assets/images/photoAdd.png" alt="相机图标" class="icon" />
              <!-- <el-image v-else :src="dataForm.logo" fit="cover" class="uploaded-image" @error="handleImageError" /> -->
            </div>
            <!-- <template v-slot:tip>
              <div class="el-upload__tip">
                {{ t("upload.tip", { format: "jpg、png、gif" }) || "只能上传jpg/png/gif文件" }}
              </div>
            </template> -->
          </el-upload>
          <el-dialog v-model="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">

            <!-- <el-image style="" w-full :src="dialogImageUrl" alt="Preview Image" fit="scale-down" /> -->
            <!-- <img  /> -->
          </el-dialog>
        </div>
        <div class="info_add maleft">
          <div class="info_add_name">
            <span style="color: rgba(255, 0, 0, 1)"> *</span>
            展厅顶部图
          </div>
          <div class="info_add_warn">请上传750*400px、JPG/JPEG/PNG的图片</div>
          <div class="add_disabled" @click.stop></div>
          <el-upload
            :action="compUploadUrl"
            :file-list="compFileList"
            :before-upload="compBeforeUploadHandle"
            :on-success="compSuccessHandle"
            :on-error="uploadErrorHandle"
            :limit="1"
            list-type="picture-card"
            :show-file-list="true"
            :auto-upload="true"
            class="brand-upload"
            :on-remove="removecompHandle"
            :on-preview="handlePictureCardPreview"
          >
            <div class="upload-box" v-if="!dataForm.compImg">
              <img src="@/assets/images/photoAdd.png" alt="相机图标" class="icon" />
              <!-- <el-image v-else :src="dataForm.compImg" fit="cover" class="uploaded-image" @error="handleImageError" /> -->
            </div>
            <!-- <template v-slot:tip>
              <div class="el-upload__tip">
                {{ t("upload.tip", { format: "jpg、png、gif" }) || "只能上传jpg/png/gif文件" }}
              </div>
            </template> -->
          </el-upload>
        </div>
        <div class="info_add" style="width: 90%">
          <div class="info_add_name">
            展厅顶部视频
          </div>
          <div class="info_add_warn">请上传不超过50M的MP4的文件</div>
          <el-upload :action="videoUploadUrl" :file-list="fileList"
                     :before-upload="videoBeforeUploadHandle"
                     :on-remove="videoRemoveHandle"
                     :on-success="videoSuccessHandle"
                     :on-error="uploadErrorHandle"
                     :limit="1"
                     :show-file-list="true"
                     class="brand-upload"
                     accept="video/*">
            <div class="upload-box">
              <img v-if="!dataForm.compVideo" src="@/assets/images/photoAdd.png" alt="相机图标" class="icon" />
              <div class="upload_video" v-else>
                <video ref="videoRef" controls width="100%" style="width: 130px; height: 130px">
                  <source :src="dataForm.compVideo" type="video/mp4" />
                  您的浏览器不支持视频播放
                </video>
                <el-button class="video_button" type="text" @click.stop="buttonDelete" style="display: flex; align-items: center;">
                  <el-icon size="20"><Delete /></el-icon>
                </el-button>
              </div>
              <!-- <el-image v-else :src="dataForm.compVideo" fit="cover" class="uploaded-image" @error="handleImageError" /> -->
            </div>
          </el-upload>
        </div>
      </div>
      <div class="operation">
        <el-button type="primary" @click="closeBasicInfo()" plain>取消</el-button>
        <el-button type="primary" @click="basicInfoSave()">确定</el-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, nextTick, onActivated } from "vue";

import baseService from "@/service/baseService";
import { IObject } from "@/types/interface";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";

const { t } = useI18n();

const videoRef = ref();

const visible = ref(false);

const dataForm = reactive({
  id: undefined as number | undefined,
  logo: "",
  compImg: "",
  compVideo: ""
});

import app from "@/constants/app";
import type { UploadProps } from "element-plus";
const uploadUrl = ref("");
const compUploadUrl = ref("");
const videoUploadUrl = ref("");
const loadVideo = ref(false);
const logFileList = ref<IObject[]>([]);
const compFileList = ref<IObject[]>([]);
const fileList = ref<IObject[]>([]);

//点击图片放大按钮查看
const dialogImageUrl = ref("");
const dialogVisible = ref(false);

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

const props = defineProps(["closeBasicInfo", "info"]);
const closeBasicInfo = () => {
  props.closeBasicInfo();
};
const buttonDelete = () => {
  dataForm.compVideo = "";
  fileList.value = [];
};
const basicInfoSave = () => {
  if (dataForm.logo === "") {
    ElMessage.error("请上传logo图片！");
    return false;
  }
  if (dataForm.compImg === "") {
    ElMessage.error("请上传展厅顶部图片！");
    return false;
  }
 if(loadVideo.value){
  if (dataForm.compVideo === "") {
    ElMessage.error("文件上传中，请稍后再试！");
    return false;
  }
 }
  baseService.post("/noc/nocuser/updateNocUserBasic", dataForm).then((res) => {
    if (res.code == 0) {
      ElMessage.success({
        message: t("prompt.success") || "保存成功",
        duration: 500
      });
      //刷新
      closeBasicInfo();
    }
  });
};
// 上传之前
const beforeUploadHandleLog = (file: IObject) => {
  if (file.type !== "image/jpg" && file.type !== "image/jpeg" && file.type !== "image/png") {
    ElMessage.error(t("upload.tip", { format: "jpg、png、jpeg" }) || "只能上传jpg/png/jpeg文件");
    return false;
  }
  // 限制图片大小为 2MB
  const maxSize = 2 * 1024 * 1024;
  if (file.size > maxSize) {
    ElMessage.error("上传的图片大小不能超过 2MB，请重新选择！");
    return false;
  }

  return true;
};
const compBeforeUploadHandle = (file: IObject) => {
  if (file.type !== "image/jpg" && file.type !== "image/jpeg" && file.type !== "image/png") {
    ElMessage.error(t("upload.tip", { format: "jpg、png、jpeg" }) || "只能上传jpg/png/jpeg文件");
    return false;
  }

  // 限制图片大小为 2MB
  const maxSize = 2 * 1024 * 1024;
  if (file.size > maxSize) {
    ElMessage.error("上传的图片大小不能超过 2MB，请重新选择！");
    return false;
  }

  return true;
};
const videoBeforeUploadHandle = (file: IObject) => {
  if (file.type !== "video/mp4") {
    ElMessage.error(t("upload.tip", { format: "jmp4" }) || "只能上传mp4文件");
    return false;
  }

  // 限制视频大小为 50MB
  const maxSize = 50 * 1024 * 1024;
  if (file.size > maxSize) {
    ElMessage.error("上传的视频大小不能超过 50MB，请重新选择！");
    return false;
  }
  loadVideo.value = true
  return true;
};
// 初始化方法
const init = (id?: number | undefined) => {
  loadVideo.value = false
  visible.value = true;
  dataForm.id = id;
  uploadUrl.value = `${app.api}/sys/oss/upload`;
  compUploadUrl.value = `${app.api}/sys/oss/upload`;
  videoUploadUrl.value = `${app.api}/sys/oss/upload`;
  fileList.value = [];
  compFileList.value = [];
  logFileList.value = [];

  // 如果是编辑，则获取品牌信息
  if (id) {
    baseService.get(`/base/basebrand/info/${id}`).then((res) => {
      if (res && res.code === 0) {
        const data = res.data;
        dataForm.logo = data.logo;
        dataForm.compImg = data.compImg;
        dataForm.compVideo = data.compVideo;
      }
    });
  }
  // console.log("props.info,props.info", props.info);
  if (props.info.compImg) {
    console.log("props.info,props.compImg", props.info.compImg);
    dataForm.compImg = props.info.compImg;
    compFileList.value = [
      {
        name: "展厅顶部图",
        url: props.info.compImg
      }
    ];
  }
  if (props.info.compVideo) {
    console.log("props.info,props.info.compVideo", props.info.compVideo);
    dataForm.compVideo = props.info.compVideo;
  }
  if (props.info.logo) {
    console.log("props.info,props.info.logo", props.info.logo);
    dataForm.logo = props.info.logo;
    logFileList.value = [
      {
        name: "公司logo",
        url: props.info.logo
      }
    ];
  }
};

const removeHandleLog = (file, fileList) => {
  console.log("文件已删除:", file);
  dataForm.logo = "";
  logFileList.value = [];
};
// 上传成功
const successHandleLog = (res: IObject, file: IObject) => {
  if (res.code !== 0) {
    return ElMessage.error(res.msg);
  }

  // 设置图片URL
  dataForm.logo = res.url;
  console.log("图片上传成功:", res);
  // 【新增】清空 fileList，确保下次可重新上传
  logFileList.value = [res];

  ElMessage.success({
    message: t("prompt.success") || "上传成功",
    duration: 500
  });
};
const removecompHandle = () => {
  dataForm.compImg = "";
  compFileList.value = [];
};
const compSuccessHandle = (res: IObject, file: IObject) => {
  if (res.code !== 0) {
    return ElMessage.error(res.msg);
  }

  // 设置图片URL
  dataForm.compImg = res.url;
  compFileList.value = [res];

  ElMessage.success({
    message: t("prompt.success") || "上传成功",
    duration: 500
  });
};
const videoRemoveHandle = () => {
  loadVideo.value = false;
};
const videoSuccessHandle = (res: IObject, file: IObject) => {
  if (res.code !== 0) {
    return ElMessage.error(res.msg);
  }
  // 设置图片URL
  dataForm.compVideo = res.url;
  loadVideo.value = false

  // 【新增】清空 fileList，确保下次可重新上传
  fileList.value = [];
  // 手动触发imgUrl字段的验证更新
  nextTick(() => {
    if (videoRef.value) {
      videoRef.value.load();
    }
  });

  ElMessage.success({
    message: t("prompt.success") || "上传成功",
    duration: 500
  });
};

// 上传错误处理
const uploadErrorHandle = (error: any) => {
  console.error("上传失败:", error);
  ElMessage.error("图片上传失败，请重试");
};

// 图片加载错误
const handleImageError = () => {
  ElMessage.error("加载失败");
};

// 组件挂载时执行初始化操作
onMounted(() => {
  console.log("买家客户列表页面已加载");
});
onActivated(() => {
  console.log("页面已显示");
});
defineExpose({
  init
});
</script>
<style lang="less" >
.basic-information-page {
  width: 100vw;
  height: 100vh;
  z-index: 999;
  opacity: 1;
  background: rgba(56, 56, 56, 0.5);
  position: fixed;
  top: 0;
  left: 0;

  display: flex;
  align-items: center;
  justify-content: center;
  .pop_up {
    width: 800px;
    height: 600px;
    background: rgba(255, 255, 255, 1);
    .pop_up_top {
      width: 100%;
      height: 52px;
      position: relative;
      // padding-top: 16px;
      // box-sizing: border-box;
      display: flex;
      align-items: center;
      // justify-content: center;

      // background: url("@/assets/images/infoBack.png") no-repeat top left;
      // background-size: 100% auto;
      // .pop_up_left {
      //   width: 100px;
      //   height: 3px;
      //   border-radius: 2px;
      //   background: linear-gradient(to right, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1));
      // }
      .pop_up_name {
        margin: 0 20px;
        font-size: 18px;
        font-weight: 400;
        letter-spacing: 0px;
        line-height: 38.4px;
        color: rgb(0, 0, 0);
      }
      // .pop_up_right {
      //   width: 100px;
      //   height: 3px;
      //   border-radius: 2px;
      //   background: linear-gradient(to right, rgba(255, 255, 255, 1), rgba(255, 255, 255, 0));
      // }
      .top_right {
        position: absolute;
        top: 23px;
        right: 20px;
        width: 14px;
        height: 14.45px;
        cursor: pointer;
        .el-icon {
          color: rgb(139, 139, 139);
          font-size: 24px;
        }
        .close_icon {
          width: 14px;
        }
      }
    }

    .pop_up_info {
      display: flex;
      flex-wrap: wrap;
      padding: 35px 0 0 50px;
      box-sizing: border-box;
      position: relative;
      .info_add {
        width: 300px;
        height: 142px;
        margin-bottom: 26px;
        position: relative;
        .info_add_name {
          font-size: 16px;
          font-weight: 400;
          letter-spacing: 0px;
          line-height: 23.17px;
          color: rgba(56, 56, 56, 1);
        }
        .info_add_warn {
          font-size: 14px;
          font-weight: 400;
          letter-spacing: 0px;
          line-height: 20.27px;
          color: rgba(168, 171, 178, 1);
          margin-bottom: 6px;
        }
        .upload_video {
          display: flex;
          border: 1px solid #dcdfe6;
          border-radius: 6px;
          .video_button {
            height: 140px;
            width: 40px;
            display: flex;
            align-items: flex-start;
            justify-content: center;
            color: #000;
            // background-color: aqua;
          }
        }
        .add_disabled {
          position: absolute;
          top: 50px;
          left: 80px;
          width: 100px;
          height: 100px;
          background-color: rgb(255, 255, 255);
          z-index: 99;
        }
        .el-upload--picture-card {
          border-color: rgba(255, 255, 255, 0);
          background-color: rgba(255, 255, 255, 0);
          width: 80px;
          height: 80px;
        }
        .el-upload-list--picture-card .el-upload-list__item {
          margin-top: 10px;
          width: 80px;
          height: 80px;
        }
        // .el-upload-list--picture-card .el-progress {
        //   width: 60px;
        //   height: 60px;
        // }
        // .basic-information-page .pop_up .pop_up_info .info_add .el-upload-list--picture-card .el-progress {
        //   width: 60px;
        //   height: 60px;
        // }

        .icon {
          width: 80px;
        }
        .uploaded-image {
          width: 80px;
          height: 80px;
        }
        .el-upload {
          margin-top: 10px;
        }
        .upload_img {
          width: 80px;
        }
      }
      .maleft {
        margin-left: 100px;
      }

    }
    .operation {
      position: relative;
      top: 120px;
      left: 620px;
    }
  }
}
</style>
